package org.bsuir.filespocket.service;

import org.bsuir.filespocket.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Collections;

@Transactional
@Repository
public class SimpleUserDAO implements UserDAO {

    @PersistenceContext
    private EntityManager em;

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        List<User> results = em.createQuery("select r from User as r").getResultList();
        if (results == null) {
            results = Collections.EMPTY_LIST;
        }
        return results;
    }

    public void saveUser(User addUser) {
        em.merge(addUser);//em.persist(addUser);
    }

    @Transactional(readOnly = true)
    public User findUser(int userId) {
        return em.find(User.class, userId);
    }

    public void deleteUser(int userId) {
        em.createQuery("delete from User as u where u.id=:userId").setParameter("userId", userId).executeUpdate();
    }

}
